import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/pages/HomePage.vue'
import UserLoginPage from '@/pages/user/UserLoginPage.vue'
import UserRegisterPage from '@/pages/user/UserRegisterPage.vue'
import userManagePage from '@/pages/admin/UserManagePage.vue'
import pictureManagePage from '@/pages/admin/PictureManagePage.vue'
import addPicturePage from '@/pages/picture/AddPicturePage.vue'
import PictureDetailPage from '@/pages/picture/PictureDetailPage.vue'
import addBatchPicturePage from '@/pages/picture/AddBatchPicturePage.vue'
import SpaceManagePage from '@/pages/admin/SpaceManagePage.vue'
import CarouselConfigPage from '@/pages/admin/CarouselConfigPage.vue'
import AddSpacePage from '@/pages/space/AddSpacePage.vue'
import MySpacePage from '@/pages/space/MySpacePage.vue'
import SpaceDetailPage from '@/pages/space/SpaceDetailPage.vue'
import SearchPicturePage from '@/pages/space/SearchPicturePage.vue'
import SpaceAnalyzePage from '@/pages/space/SpaceAnalyzePage.vue'
import SpaceUserManagePage from "@/pages/space/SpaceUserManagePage.vue";
import { useLoginUserStore } from '@/stores/useUserLoginStore';
import UnderDevelopment from '../pages/UnderDevelopment.vue'
import AnimeGalleryPage from '../pages/AnimeGalleryPage.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/anime',
      name: '二次元',
      component: AnimeGalleryPage,
      meta: {
        title: '二次元图片'
      }
    },
    {
      path: '/ai',
      name: 'ai',
      component: () => import('@/pages/ai/index.vue'),
      meta: {
        layout: 'blank',
        title: 'AI助手',
        requireAuth: true
      }
    },
    {
      path: '/ai/chat/:id',
      name: 'aiChat',
      component: () => import('@/pages/ai/index.vue'),
      meta: {
        layout: 'blank',
        title: 'AI助手',
        requireAuth: true
      },
      props: true
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/picture/addPicture',
      name: '创建图片',
      component: addPicturePage,
      meta: {
        requireAuth: true
      },
    },
    {
      path: '/picture/batch',
      name: '批量上传',
      component: addBatchPicturePage,
    },
    {
      path: '/user/login',
      name: '用户登录',
      component: UserLoginPage,
    },
    {
      path: '/user/register',
      name: '用户注册',
      component: UserRegisterPage,
    },
    {
      path: '/mySpace',
      name: '我的空间',
      component: MySpacePage,
    },

    {
      path: '/admin/userManagePage',
      name: '用户管理',
      component: userManagePage,
    },
    {
      path: '/searchPicture',
      name: '图片搜索',
      component: SearchPicturePage,
    },
    {
      path: '/admin/spaceManage',
      name: '空间管理',
      component: SpaceManagePage,
    },
    {
      path: '/admin/carouselConfig',
      name: '轮播图配置',
      component: CarouselConfigPage,
      meta: {
        requireAuth: true,
        requireAdmin: true
      }
    },
    {
      path: '/addSpace',
      name: '创建空间',
      component: AddSpacePage,
    },
    {
      path: '/admin/pictureManagePage',
      name: '图片管理',
      component: pictureManagePage,
    },
    {
      path: '/spaceAnalyze',
      name: '空间分析',
      component: SpaceAnalyzePage,
    },
    {
      path: '/spaceUserManage/:id',
      name: '空间成员管理',
      component: SpaceUserManagePage,
      props: true,
    },

    {
      path: '/space/:id',
      name: '空间详情',
      component: SpaceDetailPage,
      props: true,
    },
    {
      path: '/picture/:id',
      name: '图片详情',
      component: PictureDetailPage,
      props: true,
    },
    {
      path: '/showPicture/:id',
      name: '图片分析',
      component: PictureDetailPage,
      props: true,
    },
    {
      path: '/under-development',
      name: 'UnderDevelopment',
      component: UnderDevelopment,
      meta: {
        layout: 'blank',
        title: '功能开发中',
        requiresAuth: false
      }
    },
  ],
})

// 全局导航守卫
router.beforeEach(async (to, from, next) => {
  // 显示加载页面
  const loadingEvent = new CustomEvent('route-loading-start', {
    detail: { to, from }
  })
  window.dispatchEvent(loadingEvent)
  
  const loginUserStore = useLoginUserStore()
  
  // 如果store中没有用户id，尝试从后端获取登录状态
  if (!loginUserStore.loginUser.id) {
    await loginUserStore.fetchLoginUser()
  }
  
  const isLoggedIn = loginUserStore.loginUser.id
  const isAdmin = loginUserStore.loginUser.userRole === 'admin'

  // 检查是否需要登录权限
  if (to.meta.requireAuth) {
    if (!isLoggedIn) {
      // 如果需要登录但未登录，重定向到登录页
      next({
        path: '/user/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 检查是否需要管理员权限
    if (to.meta.requireAdmin && !isAdmin) {
      // 如果需要管理员权限但不是管理员，重定向到首页
      next('/')
      return
    }
  }

  // 继续路由导航
  next()
})

router.afterEach((to, from) => {
  // 给一个小延迟，确保新页面已经渲染
  setTimeout(() => {
    // 隐藏加载页面
    const loadedEvent = new CustomEvent('route-loading-end', {
      detail: { to, from }
    })
    window.dispatchEvent(loadedEvent)
  }, 2000) // 500ms 的延迟，可以根据需要调整
})

export default router
